package com.example.blog.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.blog.common.Result;
import com.example.blog.entity.Blog;
import com.example.blog.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ganggang
 * @since 2022-02-09
 */
@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    BlogService blogService;

    @GetMapping("/list")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage){

//        System.out.println(token);
        Page<Blog> blogPage = new Page<>(currentPage,5);
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.orderByDesc("created");
        IPage<Blog> page = blogService.page(blogPage, blogQueryWrapper);
        return Result.succ(page);
    }

    @GetMapping("/{id}")
    public Result detail(@PathVariable(name = "id") Long id){
        Blog byId = blogService.getById(id);

        return Result.succ(byId);
    }

    @PostMapping("/edit")
    public Result edit(@RequestBody Blog blog){
        blog.setCreated(LocalDateTime.now());
            boolean b = blogService.saveOrUpdate(blog);
            if (b){
                return Result.succ(null);
            }else {
                return Result.fail(null);
            }


    }
}
